package datastructure.sparsearray;

/**
 * 稀疏数组
 * @author lbw
 */
public class SparseArray {
    public static void main(String[] args) {
        //初始化原数组
        int[][] array = new int[11][11];
        array[1][2] = 1;
        array[2][4] = 2;
        for(int[] row : array){
            for(int item : row){
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }
        System.out.println("---------> 二维数组转稀疏数组");
        int num = 0;
        for (int i = 0; i < array.length; i++){
            for (int j = 0; j < array[0].length; j++){
                if (array[i][j] != 0){
                    num++;
                }
            }
        }
        int[][] sparseArray = new int[num+1][3];
        sparseArray[0][0] = array.length;
        sparseArray[0][1] = array[0].length;
        sparseArray[0][2] = num;

        for (int[] row : sparseArray) {
            for (int item : row) {
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }
        int count = 0;
        for (int i = 0; i < array.length; i++){
            for (int j = 0; j < array[0].length; j++){
                if (array[i][j] != 0){
                    count++;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = array[i][j];
                }
            }
        }
    }
}
